package com.skydroid.rcsdkdemo;

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

/**
 * 简单UDP发送测试活动
 * 用于测试UDP消息发送功能，直接发送固定消息
 */
public class SimpleUDPSender extends AppCompatActivity {

    private static final String SERVER_ADDRESS = "192.168.144.104";
    private static final int SERVER_PORT = 8888;
    private static final String TEST_MESSAGE = "Test message";
    
    private TextView tvStatus;
    private UDPMessageSender messageSender;
    private Handler handler;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_simple_udp_sender);
        
        tvStatus = findViewById(R.id.tv_status);
        handler = new Handler(Looper.getMainLooper());
        
        // 延迟2秒初始化并发送消息，给连接留出时间
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                initMessageSender();
                sendTestMessage();
            }
        }, 2000);
    }
    
    private void initMessageSender() {
        tvStatus.setText("正在初始化UDP发送器...");
        messageSender = new UDPMessageSender(SERVER_ADDRESS, SERVER_PORT);
        messageSender.setOnMessageReceivedListener(new UDPMessageSender.OnMessageReceivedListener() {
            @Override
            public void onMessageReceived(String message) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        tvStatus.setText("收到响应: " + message);
                    }
                });
            }
        });
    }
    
    private void sendTestMessage() {
        // 再延迟3秒发送消息，确保连接已经建立
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                boolean success = messageSender.sendMessage(TEST_MESSAGE);
                if (success) {
                    tvStatus.setText("已发送消息: " + TEST_MESSAGE);
                    Toast.makeText(SimpleUDPSender.this, "消息已发送", Toast.LENGTH_SHORT).show();
                } else {
                    tvStatus.setText("发送消息失败");
                    Toast.makeText(SimpleUDPSender.this, "发送失败", Toast.LENGTH_SHORT).show();
                }
            }
        }, 3000);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (messageSender != null) {
            messageSender.close();
        }
        handler.removeCallbacksAndMessages(null);
    }
} 